package com.lanou3g.zjl.chating.home.chatwindow;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.EMChatRoomChangeListener;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatRoom;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.GroupReomveListener;
import com.easemob.util.PathUtil;
import com.lanou3g.zjl.chating.R;
import com.lanou3g.zjl.chating.base.BaseFragment;
import com.lanou3g.zjl.chating.home.chatwindow.child.BigExpressionFragment;
import com.lanou3g.zjl.chating.home.chatwindow.child.ChatWindowFrgMenu;
import com.lanou3g.zjl.chating.home.chatwindow.child.ChatWindowFrgRv;
import com.lanou3g.zjl.chating.home.chatwindow.child.ChatWindowFrgRvAdapter;
import com.lanou3g.zjl.chating.home.chatwindow.child.ChatWindowFrgTitle;
import com.lanou3g.zjl.chating.home.chatwindow.child.ChatWindowFrgVoice;
import com.lanou3g.zjl.chating.home.chatwindow.child.ExpressionPagerAdapter;
import com.lanou3g.zjl.chating.home.chatwindow.child.MyMediaRecorder;
import com.lanou3g.zjl.chating.home.chatwindow.child.NormalExpressionFragment;
import com.lanou3g.zjl.chating.home.friends.EaseConstant;
import com.lanou3g.zjl.chating.home.friends.GroupInfoActivity;
import com.lanou3g.zjl.chating.home.setting.BaiduMapActivity;
import com.lanou3g.zjl.chating.utils.EaseCommonUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by dllo on 15/11/20.
 */
public class ChatWindowFragment extends BaseFragment {

    /**
     * 消息类型
     */
    private static final int TEXT = 0;
    private static final int VOICE = 1;
    private static final int IMAGE = 2;

    private static int RESULT_LOAD_IMAGE = 100;
    private static int CAMERA_RESULT = 200;
    private static int REQUEST_CODE_SELECT_FILE = 300;
    private static int REQUEST_CODE_MAP = 400;

    private EMConversation conversation;
    private List<EMMessage> list;
//    private EMMessage message;

    private int chatType;   // 聊天类型
    private int type = 0;
    private boolean menuAppear = true; // 菜单是否弹出
    private boolean expressionAppear = true; // 表情栏是否弹出
    private boolean isvoice = false; // 是否在录音
    private String picturePath; // 图片路径
    private File cameraFile = null;  // 照片路径
    private String chatFriends; // 聊天对象
    private String editStr;     // 输入的文字
//    private FragmentManager fragmentManager;
    private AnimationDrawable ad; // 录制语音的动画
    private MyMediaRecorder recorder; // 录制语音的控件
    private String voiceFilePath; // 录音文件路径
    private int voiceTimeLength; // 录音时长
    private EMChatRoomChangeListener chatRoomChangeListener; // 聊天室事件监听
    private GroupListener groupListener;

    @Bind(R.id.cwfRv_recyclerView)
    RecyclerView cwfRv_recyclerView;

    private ChatWindowFrgRvAdapter chatWindowFrgRvAdapter;

    @Bind(R.id.cwf_Title)
    ChatWindowFrgTitle cwf_Title;
    @Bind(R.id.cwf_Rv)
    ChatWindowFrgRv cwf_Rv;
    @Bind(R.id.cwf_Voice)
    ChatWindowFrgVoice cwf_Voice;
    @Bind(R.id.cwf_Menu)
    ChatWindowFrgMenu cwf_Menu;
    @Bind(R.id.chat_Et)
    EditText chat_Et;
    @Bind(R.id.chatwindowMenu_Btn)
    Button chatwindowMenu_Btn;
    @Bind(R.id.sendImg_Btn)
    Button sendImg_Btn;
    @Bind(R.id.takePhoto_Btn)
    Button takePhoto_Btn;
    @Bind(R.id.menuAppear_Rela) // 可弹出的菜单
            RelativeLayout menuAppear_Rela;
    @Bind(R.id.expressionMenu_Ll) // 可弹出的表情
            LinearLayout expressionMenu_Ll;

    @Bind(R.id.tabLayout)
    TabLayout tabLayout;
    @Bind(R.id.viewPager)
    ViewPager viewPager;

    @Bind(R.id.groupInformation_Btn)
    Button groupInformation_Btn;

    @Bind(R.id.cwfVoice_Iv)  // 录制语音的img
            ImageView cwfVoice_Iv;
    @Bind(R.id.voiceNotify_Tv)
    TextView voiceNotify_Tv; //  录制语音的提示
    @Bind(R.id.voice_Btn)  // 按住说话
            Button voice_Btn;

    @OnClick(R.id.groupInformation_Btn)
    void intoGroupInfo() {
        Intent intent = new Intent(getActivity(), GroupInfoActivity.class);
        intent.putExtra("groupInfo", chatFriends);
        startActivity(intent);
    }

//    @OnClick(R.id.call_Btn)
//    void call() {
//        startVoiceCall();
//    }
//
//    @Bind(R.id.call_Btn)
//    Button call_Btn; // 语音通话

    @Bind(R.id.deleteAllMsg_Btn)
    Button deleteAllMsg_Btn;

    /**
     * 删除所有聊天记录
     */
    @OnClick(R.id.deleteAllMsg_Btn)
    void delete() {
        conversation = EMChatManager.getInstance().getConversation(chatFriends);
        conversation.clear();
        // 清空会话
        list = conversation.getAllMessages();
        chatWindowFrgRvAdapter.addData(list);
        cwfRv_recyclerView.smoothScrollToPosition(chatWindowFrgRvAdapter.getItemCount());
        cwf_Rv.refresh();
        EMChatManager.getInstance().clearConversation(chatFriends);
    }

    /**
     * 拍照
     */
    @OnClick(R.id.takePhoto_Btn)
    void takePhoto() {
        selectPicFromCamera();
    }

    /**
     * 发送图片
     */
    @OnClick(R.id.sendImg_Btn)
    void sendImg() {
        selectPicFromLocal();
    }

    /**
     * 发文件
     */
//    @Bind(R.id.sendFile_Btn)
//    Button sendFile_Btn;
//
//    @OnClick(R.id.sendFile_Btn)
//    void sendFile() {
//        selectFileFromLocal();
//    }

    /**
     * 发位置
     */
    @Bind(R.id.sendLocation_Btn)
    Button sendLocation_Btn;

    @OnClick(R.id.sendLocation_Btn)
    void sendLocation() {
        Intent intent = new Intent(getActivity(), BaiduMapActivity.class);
        startActivityForResult(intent, 400);
    }

    /**
     * 弹出/收回菜单
     */
    @OnClick(R.id.chatwindowMenu_Btn)
    void menuAppear() {
        if (menuAppear) {
            chatwindowMenu_Btn.startAnimation(round);
            menuAppear_Rela.setVisibility(View.VISIBLE);
            expressionMenu_Ll.setVisibility(View.GONE);
            menuAppear = false;
            expressionAppear = true;
        } else {
            menuAppear_Rela.setVisibility(View.GONE);
            menuAppear = true;
        }
    }

    @OnClick(R.id.chatwindowEp_Btn)
    void expressionMenu() {
        if (expressionAppear) {
            expressionMenu_Ll.setVisibility(View.VISIBLE);
            menuAppear_Rela.setVisibility(View.GONE);
            expressionAppear = false;
            menuAppear = true;
        } else {
            expressionMenu_Ll.setVisibility(View.GONE);
            expressionAppear = true;
        }
    }

    private Animation round; // 菜单旋转的动画
    private Handler handler;
    @Bind(R.id.chatwindowEp_Btn)
    Button chatwindowEp_Btn;

    @OnClick(R.id.chat_Btn)
    void send() {
        switch (type) {
            case TEXT:
                boolean istext = getChat_Et() != null && getChat_Et().length() > 0 ? true : false;

                if (!isvoice) {
                    // 非语音 有字(直接发送)
                    if (istext) {
                        sendTextMessage(chatFriends);
                        chat_Et.setText(null);
                        emojiconName = null;

                    } else {  // 非语音  无字(变成语音状态)
                        // 发语音
                        chat_Et.setVisibility(View.GONE);
                        voice_Btn.setVisibility(View.VISIBLE);
                        chatwindowEp_Btn.setVisibility(View.GONE);
                        menuState(); // 收起表情和菜单
                        isvoice = true;

                    }
                } else {
                    // 语音状态 (切换回txt)
                    chat_Et.setVisibility(View.VISIBLE);
                    voice_Btn.setVisibility(View.GONE);
                    chatwindowEp_Btn.setVisibility(View.VISIBLE);
                    isvoice = false;

                }
                break;

            case VOICE:
                sendVoiceMessage(voiceFilePath, voiceTimeLength);
                voiceFilePath = null;
                voiceTimeLength = 0;

                break;

            case IMAGE:
                sendImageMessage(picturePath);
                cwfRv_recyclerView.smoothScrollToPosition(chatWindowFrgRvAdapter.getItemCount());
                cwf_Rv.refresh();

                picturePath = null;
                type = 0;
                break;
        }
        conversation = EMChatManager.getInstance().getConversation(chatFriends);
        list = conversation.getAllMessages();
        chatWindowFrgRvAdapter.addData(list);
        cwfRv_recyclerView.smoothScrollToPosition(chatWindowFrgRvAdapter.getItemCount());
        cwf_Rv.refresh();
    }

    @Override
    protected View getLayout(LayoutInflater inflater) {
        EventBus.getDefault().register(this); // 注册eventbus
        return inflater.inflate(R.layout.fragment_chatwindow, null);
    }

    @Override
    protected void initData() {
        msgListener(); // 接受消息的监听
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setSelectedTabIndicatorColor(0xffffffff);
        tabLayout.setTabTextColors(0xfff0f0f0, 0xffa0a0a0);
        List<String> tabList = new ArrayList<>();
        List<BaseFragment> fragmentList = new ArrayList<>();

        fragmentList.add(new NormalExpressionFragment());
        fragmentList.add(new BigExpressionFragment());

        tabList.add("表情");
        tabList.add("大表情");

        ExpressionPagerAdapter expressionPagerAdapter = new ExpressionPagerAdapter(getChildFragmentManager(), fragmentList, tabList);
        viewPager.setAdapter(expressionPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabsFromPagerAdapter(expressionPagerAdapter);

        chatWindowFrgRvAdapter = new ChatWindowFrgRvAdapter(getActivity());

        Bundle bundle = getArguments();
        // 判断单聊还是群聊
//        chatType = bundle.getInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        chatType = bundle.getInt("chattype");
        // 会话人或群组id
        chatFriends = bundle.getString("username");
//        chatFriends = getActivity().getIntent().getStringExtra("username");
        String groupName = bundle.getString("groupName");

        if (groupName != null) {
//            if (chatFriends == null) {
//                chatFriends = getActivity().getIntent().getStringExtra("groupId");
            String groupId = bundle.getString("groupId");
            chatFriends = groupId;
            groupInformation_Btn.setVisibility(View.VISIBLE);
            groupListener = new GroupListener();
            EMGroupManager.getInstance().addGroupChangeListener(groupListener);
            cwf_Title.setTitleText(groupName);
//            }
            cwf_Rv.initView(getActivity(), chatFriends, chatType);
        } else {
//            if (chatFriends == null) {
//                chatFriends = getActivity().getIntent().getStringExtra("groupId");
//                groupInformation_Btn.setVisibility(View.VISIBLE);

//                groupListener = new GroupListener();
//                EMGroupManager.getInstance().addGroupChangeListener(groupListener);
//            }
            cwf_Rv.initView(getActivity(), chatFriends, chatType);
            cwf_Title.setTitleText(chatFriends);
        }
//            cwf_Title.setTitleText(chatFriends);
//        if (chatFriends == null) {
//            chatFriends = getActivity().getIntent().getStringExtra("groupId");
//            groupInformation_Btn.setVisibility(View.VISIBLE);
//
//            groupListener = new GroupListener();
//            EMGroupManager.getInstance().addGroupChangeListener(groupListener);
//        }
//        cwf_Rv.initView(getActivity(), chatFriends, chatType);

        // 设置聊天窗口的title


        if (chatType == EaseConstant.CHATTYPE_GROUP) {

                // 监听当前会话的群聊解散被T事件
                groupListener = new GroupListener();
                EMGroupManager.getInstance().addGroupChangeListener(groupListener);

        }

        recorder = new MyMediaRecorder();

        // 延时播放动画
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        chatwindowMenu_Btn.startAnimation(round);
                        break;
                }
                return false;
            }
        });

        round = AnimationUtils.loadAnimation(getActivity(), R.anim.cw_round);
        round.setFillAfter(true);
        timer.schedule(t, 1000);

        ad = new AnimationDrawable();
        for (int i = 1; i < 10; i++) {
            int id = getResources().getIdentifier("ease_record_animate_0" + i, "drawable", getActivity().getPackageName());
            Drawable item = getResources().getDrawable(id);
            ad.addFrame(item, 100);
        }
        for (int i = 10; i < 15; i++) {
            int id = getResources().getIdentifier("ease_record_animate_" + i, "drawable", getActivity().getPackageName());
            Drawable item = getResources().getDrawable(id);
            ad.addFrame(item, 100);
        }
        ad.setOneShot(false);
        cwfVoice_Iv.setBackgroundDrawable(ad);

        // 开始录制语音时 播放动画
        voice_Btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        cwf_Voice.setVisibility(View.VISIBLE);
                        voiceNotify_Tv.setVisibility(View.VISIBLE);
                        cwfVoice_Iv.setVisibility(View.VISIBLE);
                        ad.start();
                        try {
                            recorder.startRecording(getActivity());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        voiceNotify_Tv.setText("手指上滑取消发送");
                        break;

                    case MotionEvent.ACTION_MOVE:

                        if (event.getY() < 0) {
                            voiceNotify_Tv.setText("手指松开取消发送");
                        } else {
                            voiceNotify_Tv.setText("手指上滑取消发送");
                        }
                        break;

                    case MotionEvent.ACTION_UP:
                        ad.stop();

                        cwfVoice_Iv.setVisibility(View.GONE);
                        voiceNotify_Tv.setVisibility(View.GONE);
                        cwf_Voice.setVisibility(View.GONE);

                        if (event.getY() < 0) {  //因为getY是相对控件本身的坐标，所以当<0时，手指已不再此控件上
                            Toast.makeText(getActivity(), "取消发送", Toast.LENGTH_SHORT).show();
                        } else {
                            voiceTimeLength = recorder.stopRecoding();
                            voiceFilePath = recorder.getVoiceFilePath();
                            type = 1;
                            send();
                            Toast.makeText(getActivity(), "正在发送", Toast.LENGTH_SHORT).show();
                        }
                        break;

                }
                return true;
            }
        });
    }

    /**
     * 播放菜单动画
     */
    Timer timer = new Timer();
    TimerTask t = new TimerTask() {
        @Override
        public void run() {
            handler.sendEmptyMessage(1);
        }
    };

    /**
     * 得到输入的内容
     */
    public String getChat_Et() {
        editStr = chat_Et.getText().toString().trim();
        return editStr;
    }

    //发送消息方法
// ================================================================================
    protected void sendTextMessage(String chatFriends) {
        getChat_Et();
        if (editStr != null && editStr.length() > 0) {
            EMMessage message = EMMessage.createTxtSendMessage(editStr, chatFriends);
            sendMessage(message);
        }
    }

    protected void sendBigExpressionMessage(String name, String identityCode) {
        EMMessage message = EaseCommonUtils.createExpressionMessage(chatFriends, name, identityCode);
        sendMessage(message);
    }

    protected void sendVoiceMessage(String filePath, int length) {
        EMMessage message = EMMessage.createVoiceSendMessage(filePath, length, chatFriends);
        sendMessage(message);
    }

    protected void sendImageMessage(String imagePath) {
        EMMessage message = EMMessage.createImageSendMessage(imagePath, false, chatFriends);
        sendMessage(message);
    }

    protected void sendLocationMessage(double latitude, double longitude, String locationAddress) {
        EMMessage message = EMMessage.createLocationSendMessage(latitude, longitude, locationAddress, chatFriends);
        sendMessage(message);
    }

    protected void sendVideoMessage(String videoPath, String thumbPath, int videoLength) {
        EMMessage message = EMMessage.createVideoSendMessage(videoPath, thumbPath, videoLength, chatFriends);
        sendMessage(message);
    }

    protected void sendFileMessage(String filePath) {
        EMMessage message = EMMessage.createFileSendMessage(filePath, chatFriends);
        sendMessage(message);
    }

    protected void sendMessage(EMMessage message) {
        // 如果是群聊，设置chattype,默认是单聊
        Log.d("ChatWindowFragment", "chatType:" + chatType);
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        }
//        else if (chatType == EaseConstant.CHATTYPE_CHATROOM) {
//            message.setChatType(EMMessage.ChatType.ChatRoom);
//        }
        //发送消息
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    /**
     * 接收消息的监听
     */
    public void msgListener() {
        EMChatManager.getInstance().registerEventListener(
                new EMEventListener() {

                    @Override
                    public void onEvent(EMNotifierEvent event) {

                        switch (event.getEvent()) {
                            case EventNewMessage: // 接收新消息
                            {
                                Log.d("ChatWindowFragment", "收到消息");
                                conversation = EMChatManager.getInstance().getConversation(chatFriends);
                                list = conversation.getAllMessages();
                                chatWindowFrgRvAdapter.addData(list);

                                cwfRv_recyclerView.smoothScrollToPosition(chatWindowFrgRvAdapter.getItemCount());
                                cwf_Rv.refresh();
                                break;
                            }
                            case EventDeliveryAck: {//接收已发送回执
                                Log.d("ChatWindowFragment", "已发送");
                                break;
                            }
//
//                            case EventNewCMDMessage: {//接收透传消息
//
//                                break;
//                            }
//
//                            case EventReadAck: {//接收已读回执
//
//                                break;
//                            }
//
//                            case EventOfflineMessage: {//接收离线消息
//                                List<EMMessage> messages = (List<EMMessage>) event.getData();
//                                break;
//                            }
//
//                            case EventConversationListChanged: {//通知会话列表通知event注册（在某些特殊情况，SDK去删除会话的时候会收到回调监听）
//
//                                break;
//                            }

                            default:
                                break;
                        }
                    }
                }
        );
    }

    /**
     * 得到多种返回值
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                picturePath = cursor.getString(columnIndex);
                cursor.close();

                if (picturePath != null) {
                    type = 2;
                    send();
                }
            } else if (requestCode == CAMERA_RESULT) { // 发送照片
                if (cameraFile != null && cameraFile.exists())
                    sendImageMessage(cameraFile.getAbsolutePath());
            }
        } else if (requestCode == REQUEST_CODE_MAP) { // 地图
            double latitude = data.getDoubleExtra("latitude", 0);
            double longitude = data.getDoubleExtra("longitude", 0);
            String locationAddress = data.getStringExtra("location");
            if (locationAddress != null && !locationAddress.equals("")) {
//                    sendLocationMessage(latitude, longitude, locationAddress);
                chat_Et.setText(locationAddress);
                sendTextMessage(chatFriends);
            } else {
                Toast.makeText(getActivity(), R.string.unable_to_get_loaction, Toast.LENGTH_SHORT).show();
            }

        }
    }

    /**
     * 选择文件
     */
    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //19以后这个api不可用，demo这里简单处理成图库选择图片
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }

    /**
     * 照相获取图片
     */
    protected void selectPicFromCamera() {

        cameraFile = new File(PathUtil.getInstance().getImagePath(), EMChatManager.getInstance().getCurrentUser()
                + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        startActivityForResult(
                new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)),
                CAMERA_RESULT);
    }

    /**
     * 从图库获取图片
     */
    protected void selectPicFromLocal() {

        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, RESULT_LOAD_IMAGE);
    }

    /**
     * 判断菜单弹出状态
     */
    public int menuState() {
        if (menuAppear_Rela.getVisibility() == View.VISIBLE) {
            menuAppear_Rela.setVisibility(View.GONE);
            return 0;
        }
        if (expressionMenu_Ll.getVisibility() == View.VISIBLE) {
            expressionMenu_Ll.setVisibility(View.GONE);
            return 1;
        }
        return 2;
    }

    /**
     * 聊天室创建
     */
    protected void onChatRoomViewCreation() {
        final ProgressDialog pd = ProgressDialog.show(getActivity(), "", "Joining......");
        EMChatManager.getInstance().joinChatRoom(chatFriends, new EMValueCallBack<EMChatRoom>() {

            @Override
            public void onSuccess(final EMChatRoom value) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity().isFinishing() || !chatFriends.equals(value.getUsername()))
                            return;
                        pd.dismiss();
                        EMChatRoom room = EMChatManager.getInstance().getChatRoom(chatFriends);
//                        if (room != null) {
//                            titleBar.setTitle(room.getName());
//                        } else {
//                            titleBar.setTitle(chatFriends);
//                        }
//                        EMLog.d(TAG, "join room success : " + room.getName());
                        addChatRoomChangeListenr();
//                        onConversationInit();
//                        onMessageListInit();
                    }
                });
            }

            @Override
            public void onError(final int error, String errorMsg) {
                // TODO Auto-generated method stub
//                EMLog.d(TAG, "join room failure : " + error);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                    }
                });
                getActivity().finish();
            }
        });
    }

    /**
     * 添加聊天室事件监听
     */
    protected void addChatRoomChangeListenr() {
        chatRoomChangeListener = new EMChatRoomChangeListener() {

            /**
             * 解散聊天室
             * */
            @Override
            public void onChatRoomDestroyed(String roomId, String roomName) {
                if (roomId.equals(chatFriends)) {
//                    showChatroomToast(" room : " + roomId + " with room name : " + roomName + " was destroyed");
                    Toast.makeText(getActivity(), " room : " + roomId + " with room name : " + roomName + " was destroyed", Toast.LENGTH_SHORT).show();
                    getActivity().finish();
                }
            }

            /**
             * 成员加入
             * */
            @Override
            public void onMemberJoined(String roomId, String participant) {
//                showChatroomToast("member : " + participant + " join the room : " + roomId);
                Toast.makeText(getActivity(), "member : " + participant + " join the room : " + roomId, Toast.LENGTH_SHORT).show();
            }

            /**
             * 聊天室成员退出
             * */
            @Override
            public void onMemberExited(String roomId, String roomName, String participant) {
//                showChatroomToast("member : " + participant + " leave the room : " + roomId + " room name : " + roomName);
                Toast.makeText(getActivity(), "member : " + participant + " leave the room : " + roomId + " room name : " + roomName, Toast.LENGTH_SHORT).show();
            }

            /**
             * 踢出聊天室成员
             * */
            @Override
            public void onMemberKicked(String roomId, String roomName, String participant) {
                if (roomId.equals(chatFriends)) {
                    String curUser = EMChatManager.getInstance().getCurrentUser();
                    if (curUser.equals(participant)) {
                        EMChatManager.getInstance().leaveChatRoom(chatFriends);
                        getActivity().finish();
                    } else {
//                        showChatroomToast("member : " + participant + " was kicked from the room : " + roomId + " room name : " + roomName);
                        Toast.makeText(getActivity(), "member : " + participant + " was kicked from the room : " + roomId + " room name : " + roomName, Toast.LENGTH_SHORT).show();
                    }
                }
            }

        };

        EMChatManager.getInstance().addChatRoomChangeListener(chatRoomChangeListener);
    }

    /**
     * 监测群组解散或者被T事件
     */
    class GroupListener extends GroupReomveListener {

        public void onUserRemoved(final String groupId, String groupName) {
            getActivity().runOnUiThread(new Runnable() {

                public void run() {
                    if (chatFriends.equals(groupId)) {
                        Toast.makeText(getActivity(), R.string.you_are_delete, Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                    }
                }
            });
        }

        public void onGroupDestroy(final String groupId, String groupName) {
            // 群组解散正好在此页面，提示群组被解散，并finish此页面
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (chatFriends.equals(groupId)) {
                        Toast.makeText(getActivity(), R.string.this_group_has_been_delete, Toast.LENGTH_SHORT).show();
                        getActivity().finish();
                    }
                }
            });
        }
    }


    /**
     * 拨打语音电话
     */
    protected void startVoiceCall() {
        if (!EMChatManager.getInstance().isConnected()) {
            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
        } else {
            startActivity(new Intent(getActivity(), CallActivity.class).putExtra("username", chatFriends)
                    .putExtra("isComingCall", false));
            // voiceCallBtn.setEnabled(false);
//            inputMenu.hideExtendMenuContainer();
        }
    }

    private String emojiconName; // 聊天内容

    public void onEvent(String datas) {
        this.emojiconName = datas;
    }

    public void onEventMainThread(Integer id) {
        Bitmap bitmap = null;
        bitmap = BitmapFactory.decodeResource(getResources(), id);
        ImageSpan imageSpan = new ImageSpan(getActivity(), bitmap);

        SpannableString spannableString =
                new SpannableString(emojiconName);

        spannableString.setSpan(imageSpan, 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (emojiconName != "delete_expression") {
            chat_Et.append(spannableString);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this); // eventbus取消注册
//        cwf_Rv.initView(getActivity(), chatFriends, chatType);
    }


}
